import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

class DioDemo extends StatefulWidget {
  const DioDemo({super.key});

  @override
  _DioDemoState createState() => _DioDemoState();
}

class _DioDemoState extends State<DioDemo> {
  List _channels = [];

  @override
  void initState() {
    super.initState();
    _getData();
  }

  _getData() async {
    // 1.创建dio实例
    Dio dio = Dio();
    // 2.发送请求
    final res = await dio.get('https://geek.itheima.net/v1_0/channels');
    // 3.处理响应数据
    _channels = res.data['data']['channels'];
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
        itemCount: _channels.length,
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          mainAxisSpacing: 10,
          crossAxisSpacing: 10,
        ),
        itemBuilder: (context, index) {
          return Container(
            alignment: Alignment.center,
            decoration: const BoxDecoration(
              color: Colors.green,
            ),
            child: Text(
              _channels[index]['name'],
              style: const TextStyle(color: Colors.white, fontSize: 16),
            ),
          );
        });
  }
}
